package com.mail.service.impl;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.mail.service.MailSenderService;
/**
 * 
 * @author yangshaojun
 *
 */
@Service
public class MailSenderServiceImpl implements MailSenderService {

	private static final Logger log = LoggerFactory.getLogger(MailSenderServiceImpl.class);
	
	@Autowired
	private JavaMailSender mailSender; 
	
	@Value("${spring.mail.username}")
	private String senderName;
	
	@Override
	public void sendSimpleMail(String toUser, String subject, String text) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo(toUser);
		message.setSubject(subject);
		message.setText(text);
		message.setFrom(senderName);
		mailSender.send(message);
	}

	@Override
	public void sendHtmlMail(String toUser, String subject, String text) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setTo(toUser);
			helper.setSubject(subject);
			helper.setText(text, true);
			helper.setFrom(senderName);
			mailSender.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sendAttachmentsMail(String toUser, String subject, String text, String filePath) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setTo(toUser);
			helper.setSubject(subject);
			helper.setText(text, true);
			helper.setFrom(senderName);
			
			FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
			String fileName = fileSystemResource.getFilename();
			helper.addAttachment(fileName, fileSystemResource);
			mailSender.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sendImageResourceMail(String toUser, String subject, String text, String imgPath, String imgId) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setTo(toUser);
			helper.setSubject(subject);
			helper.setText(text, true);
			helper.setFrom(senderName);
			
			FileSystemResource imgSystemResource = new FileSystemResource(new File(imgPath));
			helper.addInline(imgId, imgSystemResource);
			mailSender.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

}
